from turtledemo.penrose import start
from typing import Optional

from appium.webdriver.common.appiumby import AppiumBy
from loguru import logger

from appium.webdriver import WebElement
from selenium.common import StaleElementReferenceException
from selenium.webdriver.support.wait import WebDriverWait

from basic.base_driver import DRIVER


class BasePage:
    def __init__(self):
        self.driver = DRIVER

    def _locator (self,loc,wait: int = None,freq: int = 0.5)-> Optional[WebElement]:
        # loc定位元素，wait等待时间，freq等待频率，ignored_exceptions忽略异常
        return self.driver.find_element(*loc) if wait is None else \
            WebDriverWait(self.driver, wait, freq,  [StaleElementReferenceException]).until(lambda x: x.find_element(*loc))


    def _click(self,loc,wait: int = None):
        if isinstance(loc,str):
            loc = (AppiumBy.ANDROID_UIAUTOMATOR,loc)
        logger.info(f"点击元素{loc}")
        self._locator(loc,wait).click()



    def _get_phone_size(self):
        """获取手机屏幕尺寸"""
        width = self.driver.get_window_size()["width"]
        height = self.driver.get_window_size()["height"]
        return width,height

    def _swipe_up(self,duration:int = 500,csy = 0.8,cey = 0.2):
        """
        向上滑动
        :param duration: 滑动时间，单位毫秒
        :param csy: 起始坐标y轴比例，默认0.8
        :param cey: 结束坐标y轴比例，默认0.2
        :return: None
        """
        width,height = self._get_phone_size()
        start_x = 0.5
        start_y = height * csy
        end_x = 0.5
        end_y = height * cey
        return self.driver.swipe(start_x, start_y, end_x, end_y, duration)

    def _swipe_down(self,duration:int = 500,csy = 0.2,cey = 0.8):
        """
        向下滑动
        :param duration: 滑动时间，单位毫秒
        :param csy: 起始坐标y轴比例，默认0.2
        :param cey: 结束坐标y轴比例，默认0.8
        :return: None
        """
        width,height = self._get_phone_size()
        start_x = 0.5
        start_y = height * csy
        end_x = 0.5
        end_y = height * cey
        return self.driver.swipe(start_x, start_y, end_x, end_y, duration)

    def _swipe_left(self,duration:int = 500):
        """
        向左滑动
        :param duration: 滑动时间，单位毫秒
        :return: None
        """
        width,height = self._get_phone_size()
        start_x = 0.1
        start_y = 0.5
        end_x = 0.9
        end_y = 0.5
        return self.driver.swipe(start_x, start_y, end_x, end_y, duration)

    def _swipe_right(self,duration:int = 500):
        """
        向右滑动
        :param duration: 滑动时间，单位毫秒
        :return: None
        """
        width,height = self._get_phone_size()
        start_x = 0.1
        start_y = 0.5
        end_x = 0.9
        end_y = 0.5
        return self.driver.swipe(start_x, start_y, end_x, end_y, duration)
